package com.aso.common.ble;

import android.text.TextUtils;

import com.aso.common.sp.SPHelper;
import com.aso.common.utils.Utils;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.model.BleGattCharacter;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.model.BleGattService;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.itsdf07.alog.ALog;

import java.util.List;
import java.util.UUID;

import static com.inuker.bluetooth.library.Code.REQUEST_SUCCESS;

/**
 * @Description ：蓝牙Ble设备管理器 ，提供如下功能：
 * 1、扫描
 * 2、连接
 * 3、扫描并连接
 * @Author itsdf07
 * @Time 2017/11/29
 */

public class LeManager {
    private static final String TAG = "LeManager";
    private static LeManager instance;

    //ble蓝牙
    private BluetoothClient mClient;
    private SearchRequest mRequest;

    private boolean isConnecting = false;

    public static LeManager getInstance() {
        if (instance == null) {
            instance = new LeManager();
        }
        return instance;
    }

    private IBlePTTCallback mBlePTTCallback;

    public interface IBlePTTCallback {
        void onBlePttCallback(int type);


    }

    public void init() {
        //启动ble蓝牙服务
        mClient = new BluetoothClient(Utils.getApplication());
        // 扫描设备：支持经典蓝牙和BLE设备混合扫描，可自由定制扫描策略如下：
        mRequest = new SearchRequest.Builder()
                .searchBluetoothLeDevice(3000, 3)
                .searchBluetoothLeDevice(2000)
                .build();
    }

    public boolean isConnecting() {
        return isConnecting;
    }

    /**
     * 取消Ble设备的扫描
     */
    public void onStopSearch() {
        if (!isConnecting) {
            ALog.dTag(TAG, "目前并没有在扫码Ble设备，无需取消");
            return;
        }
        if (mClient == null) {
            ALog.dTag(TAG, "mClient = null，扫描取消失败！");
            return;
        }
        mClient.stopSearch();
    }

    /**
     * 扫描Ble设备
     */
    public void onScanBle() {
        if (isConnecting) {
            ALog.dTag(TAG, "onScanBle : 已经在搜索设备中，请稍候");
            return;
        }
        ALog.dTag(TAG, "onScanBle :");
        mClient.search(mRequest, new SearchResponse() {

            @Override
            public void onSearchStarted() {
                isConnecting = true;
                ALog.dTag(TAG, "onScanBle : 开始搜索Ble设备");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                if (device == null) {
                    ALog.eTag(TAG, "onDeviceFounded : device == null");
                } else {
                    ALog.dTag(TAG, "onDeviceFounded : device name = %s,mac = %s", device.getName(), device.getAddress());
                }
            }

            @Override
            public void onSearchStopped() {
                isConnecting = false;
                ALog.dTag(TAG, "onSearchStopped : ");
            }

            @Override
            public void onSearchCanceled() {
                isConnecting = false;
                ALog.dTag(TAG, "onSearchCanceled : ");
            }
        });
    }

    /**
     * 扫描Ble设备
     */
    public void onScanBleAndConnected(final String mac, IBlePTTCallback callback) {
        if (TextUtils.isEmpty(mac)) {
            ALog.dTag(TAG, "无效的BleMac地址");
            return;
        }
        onDisConnectedBle(mac);
        if (isConnecting) {
            ALog.dTag(TAG, "已经在搜索设备中，请稍候");
            return;
        }
        ALog.dTag(TAG, "...");
        mBlePTTCallback = callback;
        mClient.search(mRequest, new SearchResponse() {

            @Override
            public void onSearchStarted() {
                isConnecting = true;
                ALog.dTag(TAG, "开始搜索Ble设备");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                if (device == null) {
                    ALog.eTag(TAG, " device == null");
                    return;
                } else {
                    ALog.dTag(TAG, "device mac = %s,name = %s,mac = %s", mac,device.getName(), device.getAddress());
                }

                if (mac.equals(device.getAddress())) {
                    onStopSearch();
                    connect(mac);
                }
            }

            @Override
            public void onSearchStopped() {
                isConnecting = false;
                ALog.dTag(TAG, "...");
            }

            @Override
            public void onSearchCanceled() {
                isConnecting = false;
                ALog.dTag(TAG, "...");
            }
        });
    }

    /**
     * 连接Ble设备
     *
     * @param mac
     */
    public void connect(final String mac) {
        ALog.dTag(TAG, "mac = %s", mac);
        mClient.connect(mac, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile data) {
                ALog.dTag(TAG, "code = %s", code);
                if (code == REQUEST_SUCCESS) {
                    List<BleGattService> serviceList = data.getServices();
                    ALog.dTag(TAG, "serviceList = %s", serviceList.size());
                    for (BleGattService service : serviceList) {
                        ALog.dTag(TAG, "service = %s", service.getCharacters().size());
                        for (BleGattCharacter characteristic : service.getCharacters()) {
                            ALog.dTag(TAG, "uuid = %s", service.getUUID().toString());
                            // 打开设备通知
                            mClient.notify(mac, service.getUUID(), characteristic.getUuid(), new BleNotifyResponse() {
                                @Override
                                public void onNotify(UUID service, UUID character, byte[] value) {
                                    ALog.dTag(TAG, "value[0] = %s,service uuid = %s,character uuid = %s", value[0], service.toString(), character.toString());
                                    if (mBlePTTCallback != null) {
                                        //PTT按下：1 ，PTT松开：0
                                        mBlePTTCallback.onBlePttCallback(value[0]);
                                    }
                                }

                                @Override
                                public void onResponse(int code) {
                                    ALog.dTag(TAG, "code == %s", code);
                                    if (code == REQUEST_SUCCESS) {
                                        SPHelper.put(SPHelper.SPKeyGlobal.KEY_BLE_MAC, mac);
                                    }
                                }
                            });
                        }
                    }
                }
            }
        });
    }

    public void onDisConnectedBle(String mac) {
        mClient.disconnect(mac);
        mBlePTTCallback = null;
    }

    public void destory() {
        if (mClient != null) {
            mClient = null;
        }
        if (mRequest != null) {
            mRequest = null;
        }
        if (instance != null) {
            instance = null;
        }
    }


}
